<template>
  <div style="height: 100%; position: relative">
    <div class="message_area" ref="messagelist">
      <div v-for="(item, index) in messageList" :key="index">
        <div v-if="item.from == 'ai'" style="width: 100%; display: flex">
          <div class="ai_item">
            <div class="ai_head">
              <img src="@/assets/chat_2.png" alt="" />
            </div>
            <div class="ai_arrow"></div>
            <div class="ai_content">
              <div>{{ item.value }}</div>
            </div>
          </div>
        </div>
        <div v-if="item.from == 'user'" style="width: 100%; flex-direction: row-reverse; display: flex">
          <div class="user_item">
            <div class="user_content">
              <div>{{ item.value }}</div>
            </div>
            <div class="user_arrow"></div>
            <img class="user_head" src="@/assets/chat_1.png" alt="" />
          </div>
        </div>
      </div>
      <div v-if="loading" class="tip_text">对方正在输入中......</div>
      <div v-if="showError" class="tip_text">请稍后再试......</div>
    </div>
    <div class="send_area">
      <div class="send_input">
        <el-input
          v-model="inputValue"
          clearable
          style="border: unset"
          @keyup.native.enter="handleSendMessage"
        ></el-input>
        <div style="width: 1px; height: 20px; background-color: #ededee"></div>
        <div class="send_btn" @click="handleSendMessage">
          <i
            v-if="inputValue.length && !loading"
            class="el-icon-s-promotion"
            style="color: #155eef; cursor: pointer"
          ></i>
          <i v-else class="el-icon-s-promotion" style="color: #ddd"></i>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Vue from 'vue'
import { ACCESS_TOKEN, TENANT_ID, USER_INFO, ACCOUNT_BOOK } from '@/store/mutation-types'
import { httpAction, getAction } from '@/api/manage'
import { color } from 'echarts'
import { message } from 'ant-design-vue'
export default {
  name: 'dialogShare',
  computed: {
    ...mapGetters(['name']),
  },
  data() {
    return {
      messageList: [],
      inputValue: '',
      accountBookId: '',
      aiIndex: 0,
      loading: false,
      showError: false,
    }
  },
  created() {
    console.log('小助手启动-created')
    let list = this.$lcStorage.get('ai-message')
    if (!list || !list.length) {
      this.reset()
    } else {
      this.messageList = list
    }
    let accountBook = Vue.ls.get(ACCOUNT_BOOK)
    this.accountBookId = accountBook && accountBook.id

    // let text = [
    //   '您好，有什么我可以帮您的吗？我们很乐意回答您关于产品功能或任何其他方面的问题！',
    //   '没有，谢谢！',
    //   '好的，有什么想问的随时找我哦',
    //   '库存查询在哪里',
    //   '查询中心、库存查询、仓库库存查询，点左上角统计',
    //   '如何快速开单',
    //   '您好！关于“如何快速开单”，以下是为您提供的操作指南：选择已审核但未完成状态的销售订单。点击“生成销售单”按钮。可以选择单条或多条记录进行生成。同一条销售订单可以无限次生成销售单。如有其他问题，请随时联系我！',
    //   '单子做错了怎么办',
    //   '打开这个单据，点单据操作点红冲（作废这个单据的意思）。然后可以点单据操作复制单据，复制一个一样的重新修改保存审核即可。',
    // ]
    // for (let index = 0; index < text.length; index++) {
    //   const element = text[index]
    //   let from = index % 2 ? 'user' : 'ai'
    //   console.log(from)

    //   let time = index * 3000
    //   setTimeout(() => {
    //     this.messageList.push({
    //       from: from,
    //       value: element,
    //     })
    //   }, time)
    // }
  },
  watch: {
    messageList(val) {
      this.$lcStorage.set('ai-message', val)
      this.$nextTick(() => {
        this.$refs.messagelist.scrollTop = this.$refs.messagelist.scrollHeight
      })
    },
  },
  updated() {},
  methods: {
    reset() {
      this.loading = false
      this.showError = false
      this.messageList = [
        {
          from: 'ai',
          answer: '',
					conversationId: '',
          value: '您好，有什么我可以帮您的吗？我们很乐意回答您关于产品功能或任何其他方面的问题！',
        },
      ]
    },
    handleSendMessage() {
      if (this.inputValue && !this.loading) {
        this.messageList.push({
          from: 'user',
          value: this.inputValue,
        })
        this.handleData(this.inputValue)
        // this.handleSSEData(this.inputValue)
        this.inputValue = ''
      }
    },
    //普通请求方式
    handleData(text) {
      let that = this
      that.loading = true
      that.showError = false
      let ais = this.messageList.filter(item => item.conversationId)
			let item = ais.length > 0 ? ais[ais.length - 1] : {}
      getAction('/ai/chat', {
        answer: item.answer,
				conversationId: item.conversationId,
        msg: text,
        userId: this.accountBookId, //使用账套id当做userId
      }).then((res) => {
        that.loading = false
        if (res.success) {
          let result = res.result || {}
          that.messageList.push({
            ...result,
            from: 'ai',
            value: result.answer,
          })
        } else {
          that.showError = true
        }
      })
    },
    //sse流式请求，
    handleSSEData(text) {
      let that = this
      that.loading = true
      that.showError = false
      let baseUrl = window._CONFIG['domianURL']
      let url = `${baseUrl}/ai/chat?msg=${text}&userId=${that.accountBookId}`
      const eventSource = new EventSource(url)
      let callback = false
      eventSource.onmessage = function (event) {
        // console.log(event);
        let text = event.data
        let index = that.messageList.length - 1
        let item = that.messageList[index]
        item.value = item.value + text
        that.messageList.splice(index, 1, item)
      }
      // 监听open事件，连接建立时触发
      eventSource.onopen = function (event) {
        that.loading = false
        console.log('SSE connection opened')
        that.messageList.push({
          from: 'ai',
          value: '',
        })
        callback = true
      }
      // 监听error事件，处理连接错误
      eventSource.onerror = function (event) {
        console.log('SSE connection error:', event)
        // 在这里可以添加重连逻辑
        eventSource.close()
        that.loading = false
        if (!callback) {
          that.showError = true
        }
      }
      // 监听close事件，连接关闭时触发
      eventSource.onclose = function (event) {
        console.log('SSE connection closed')
        // 在这里可以添加重连逻辑
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.ai_item {
  justify-content: flex-end;
  display: flex;
  margin-bottom: 10px;
  max-width: calc(100% - 50px);
}
.ai_head {
  flex-shrink: 0;
  margin-right: 8px;
  width: 40px;
  height: 40px;
  background-color: #d5f5f6;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 20px;

  img {
    width: 20px;
    height: 20px;
  }
}
.ai_arrow {
  width: 0;
  height: 0;
  border-top: 0;
  border-bottom: 12px solid transparent;
  border-right: 10px solid #f2f4f7;
}
.ai_content {
  padding: 10px;
  background-color: #f2f4f7;
  font-size: 14px;
  color: #111;
  line-height: 20px;
  border-radius: 0 15px 15px 15px;
}
.user_item {
  justify-content: flex-end;
  display: flex;
  margin-bottom: 10px;
  max-width: calc(100% - 50px);
}
.user_head {
  flex-shrink: 0;
  margin-left: 8px;
  width: 40px;
  height: 40px;
}
.user_arrow {
  width: 0;
  height: 0;
  border-top: 0;
  border-bottom: 12px solid transparent;
  border-left: 10px solid #e1effe;
}
.user_content {
  padding: 10px;
  background-color: #e1effe;
  font-size: 14px;
  color: #111;
  line-height: 20px;
  border-radius: 15px 0 15px 15px;
}
.message_area {
  height: calc(100% - 45px);
  // padding-bottom: 60px;
  overflow: hidden;
  overflow-y: scroll;
}
.send_area {
  width: 100%;
  height: 45px;
  // background-color: #181818;
  position: absolute;
  bottom: 0;
}
.send_input {
  border: #ededee solid 1px;
  height: 40px;
  border-radius: 10px;
  display: flex;
  align-items: center;
}
.send_btn {
  width: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 22px;
}
.tip_text {
  width: 100%;
  text-align: center;
  height: 30px;
  line-height: 30px;
}

::v-deep .el-input {
  width: calc(100% - 50px);
  .el-input__inner {
    border: unset;
    height: 38px;
    border-radius: 12px;
  }
  .el-input__inner:hover {
    border: unset;
  }
}
</style>

